﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.IO;

namespace ElectronicJournal.Account.AuthorAccount
{
    public delegate void SendingDelegate(Guid authorGuid, string pubName);

    public delegate void ChangingStateDelegate(Guid authorGuid, string statePub, Guid pubId);

    public class Coauthor
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string thirdName { get; set; }
        public string phoneNumber { get; set; }
        public string email { get; set; }
    }

   

    public partial class NewPublication : System.Web.UI.Page
    {
        public static event SendingDelegate SendingDelegateEvent;
        private Guid authorGuid;
        protected void Page_Init(object sender, EventArgs e)
        {
            InitializeScientificDirections();
            InitializePublicationTypes();
            InitializeUDCs();
        }

        protected void InitializeScientificDirections()
        {
            List<ScientificDirection> scientificDirections = EJournalRepository.Instance.GetAllScientificDirections().ToList();
            foreach (var scientificDir in scientificDirections)
            {
                ScientificDropDownList.Items.Add(new ListItem(scientificDir.Title, scientificDir.Id.ToString()));
            }
        }

        protected void InitializePublicationTypes()
        {
            List<PublicationType> publicationTypes = EJournalRepository.Instance.GetAllPublicationTypes().ToList();
            foreach (var pubType in publicationTypes)
            {
                TypeDropDownList.Items.Add(new ListItem(pubType.Title, pubType.Id.ToString()));
            }
        }

        protected void InitializeUDCs()
        {
            //List<UDC> udcs = EJournalRepository.Instance.GetAllUDCs().ToList();
            //foreach (var udc in udcs)
            //{
            //    UDCDropDownList.Items.Add(new ListItem(udc.UDC1, udc.UDCId.ToString()));
            //}
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["Update"] = Session["Update"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            }

            if (Request["coauthors"] != null)
            {
                var obj = Request["coauthors"];

                SaveCoauthors(obj.ToString());
                
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.End();
            }
        }


        protected void SaveCoauthors(string jSonStringCoauthors)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            var resultObjectsCoauthors = jsSerializer.Deserialize(jSonStringCoauthors, typeof(Coauthor[]));
            var resultCoauthorsList = new List<Coauthor>((IEnumerable<Coauthor>)resultObjectsCoauthors);
            
            Cache["currentCoauthors"] = resultCoauthorsList;
        }

        private IEnumerable<Coauthor> GetCoauthorsFromCache()
        {
            var cacheData = Cache.Get("currentCoauthors");
            var coauthors = (IEnumerable<Coauthor>)cacheData;
            Cache.Remove("currentCoauthors");

            return coauthors;
        }

        protected void AddNewPublication(object sender, EventArgs e)
        {
            try
            {
                //if (Session["Update"].ToString() == ViewState["Update"].ToString())
                {
                    string folder = Server.MapPath("..") + "\\files\\publications\\";

                    authorGuid = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
                    
                    var coauthors = GetCoauthorsFromCache();
                    
                    EJournalRepository.Instance.AddPublication(authorGuid, TitleRussianTextBox.Text, TitleEnglishTextBox.Text,
                        Guid.Parse(ScientificDropDownList.SelectedItem.Value), Guid.Parse(TypeDropDownList.SelectedItem.Value),
                        UDCTextBox.Text, SummaryRussianTextBox.Text, SummaryEnglishTextBox.Text,
                        KeywordsRussianTextBox.Text, KeywordsEnglishTextBox.Text, SpecialityTextBox.Text, UploadFileOnServer(FileArticleUpload, folder),
                        UploadFileOnServer(FileExpertUpload, folder), UploadFileOnServer(FileLetterUpload, folder), DateTime.Now, 1, coauthors);
                        Session["Update"] = Server.UrlEncode(System.DateTime.Now.ToString());

                        SendingDelegateEvent(authorGuid, TitleEnglishTextBox.Text);
                        Response.Redirect("MyAccount.aspx");
                }
            }
            catch (NullReferenceException nrEx)
            {
                
            }
        }

        private string UploadFileOnServer(FileUpload uploader, string folder)
        {
            System.IO.Directory.CreateDirectory(folder);
            string FileName = System.IO.Path.GetFileName(uploader.FileName);
            if (!string.IsNullOrEmpty(FileName))
            {
                FileName = FileName.Insert(FileName.LastIndexOf("."), authorGuid.ToString());
                if ((uploader.PostedFile != null) && (uploader.PostedFile.ContentLength > 0))
                {
                    uploader.PostedFile.SaveAs(folder + FileName);
                }
            }
            return FileName;
        }
    }
}